package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住信息
     *
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.通过身份证和床位状态信息检验老人是否已经入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        //当前老人已经入住,直接返回
        if (elder != null){
            return;
        }
        //2.老人未入住，则更新床位状态信息为已入住
          //2.1根据床位编号查询床位信息
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或者更新老人入住信息
        elder = insertOrUpdate(dto, bed);
        //4.新增合同数据
        insertContract(elder, dto);
        //5.新增入住信息
        CheckIn checkIn = insertElderCheckIn(elder, dto);
        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);

    }
    /**
     * 新增入住配置
     * @param dto
     */
    private void insertCheckInConfig(Long checkId,CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkId);
        checkInConfigMapper.insert(checkInConfig);
    }
    /**
     * 新增入住信息
     * @param elder
     * @param dto
     */
    private CheckIn insertElderCheckIn(Elder elder, CheckInApplyDto dto) {
        //创建入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));//老人家属信息
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    /**
     * 新增合同信息
     *
     * */
    private void insertContract(Elder  elder,CheckInApplyDto dto) {
        Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        //补全合同数据
        contract.setElderId(Integer.parseInt(elder.getId()+ ""));
        contract.setContractName(elder.getName());
        contract.setElderName(elder.getName());
        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        //判断合同的状态信息
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setSignDate(LocalDateTime.now());
        contractMapper.insert(contract);
    }

    /**
     * 新增或者更新老人入住信息
     * @param dto
     * @param bed
     * */
    private Elder insertOrUpdate(CheckInApplyDto dto,Bed  bed) {
        //准备老人数据
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(checkInElderDto, newElder);
        //补全数据
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setStatus(1);

        //查询老人状态信息，如果不为1，则更新或者新增
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo , dto.getCheckInElderDto().getIdCardNo()).ne(Elder::getStatus,1);
        //查询是否为要跟新或者新增
        Elder oldElder = elderMapper.selectOne(wrapper);
        if (oldElder != null){
            //更新老人数据
            elderMapper.updateElder(newElder);
        }else {
          //新增老人数据
            elderMapper.insert(newElder);
        }
        return newElder;
    }
    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //1.根据入住id查询入住信息
        //因为入住信息中只保存了老人id，所以需要根据入住id查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //1.2根据入住信息查询到老人的id
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, checkIn.getElderId()));
        //2.根据老人的id查询到老人的详细信息
        Elder elderInfo = elderMapper.selectElderById(elder.getId());
        //2.1从老人的身份证中获取到老人的出生年月日
        String birth = elder.getIdCardNo().substring(6, 14);
        //解析出生日期
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birth + "", dateTimeFormat);
        //计算年龄
        int age= Period.between(birthDate, LocalDate.now()).getYears();
        //封装老人相关信息
        CheckInElderVo elderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elderInfo, elderVo);
        elderVo.setAge(age);
        //3.根据老人的id查询到老人的合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        //4.根据老人id查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        //获取入住开始时间
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        //5.查询老人家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        //6.封装所有信息并返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(elderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;

    }


}
